import Vue from "vue";
import Router from "vue-router";
import HomeLayout from "@/layout/layout.vue";
// import { paths, menus } from "@/router/menu";
// 添加页面进度条
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import Watermark from "../libs/watermark";
import moment from "moment";
import store from "../store";
NProgress.configure({ showSpinner: false }); // NProgress Configuration
const paths = [];
Vue.use(Router);

//获取原型对象上的push函数
const originalPush = Router.prototype.push;
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};
//动态获取的菜单
let mainRoutes = {
  path: "/",
  component: HomeLayout,
  // name: '首页',
  meta: {
    title: "首页",
  },
  children: [
    {
      path: "/data/coding",
      component: () => import("@/views/home/data/coding"),
      meta: {
        title: "404",
        originTitle: "404",
      },
    },
  ],
};
//不需要动态获取的路由 （包括，跳转链接）
let globalRoutes = [
  {
    path: "/login",
    component: () => import("@/views/login/index"),
    meta: {
      title: "登录",
      originTitle: "登录",
    },
  },
];
let errRoute = {
  path: "*",
  component: () => import("@/views/home/data/coding"),
};
let d = [...globalRoutes, mainRoutes, errRoute];
const router = new Router({
  mode: "hash",
  routes: d,
});
for (let x of mainRoutes.children) {
  paths.push(x.path);
}
router.beforeEach(async (to, from, next) => {
  let Allmenus = store.state.index.menus;
  let user = JSON.parse(sessionStorage.getItem("user"));
  if (to.path == "/login") {
    next();
    return;
  } else if (!user) {
    next("/login");
    return;
  } else {
    NProgress.start();
    if (!Allmenus) {
      //请求菜单
      let data = await store.dispatch("index/getMenus");
      if (data.length == 0) {
        sessionStorage.removeItem("user");
        sessionStorage.removeItem("token");
        Vue.$alert("该账号无任何登录权限", "提示", { type: "error" });
        next("/login");
      }
      data.forEach((v) => {
        paths.push(v.path);
      });
      mainRoutes.children = [...mainRoutes.children, ...data];
      router.addRoutes([mainRoutes]);
      next(to.fullPath || to.path);
      return;
    } else {
      store.commit("index/setMenus", Allmenus);
      next();
    }
  }
});
router.afterEach((to) => {
  NProgress.done();
  // 添加菜单tags
  let user = JSON.parse(sessionStorage.getItem("user"));
  let day = moment().format("YYYY-MM-DD");
  let i = paths.findIndex((v) => v == to.path);
  let remove = false;
  if (i == -1) {
    remove = true;
  } else {
    router.app.$store.dispatch("tagsView/addView", to);
    router.app.$store.commit("tagsView/setCurrentView", to);
  }
  // Watermark.set(user.loginName, day, remove)
  // 更改标题
  router.app.$store &&
    router.app.$store.commit("index/setCurrentTopMenu", to.fullPath);
  window.document.title =
    (to.meta.title || "未命名") + " | " + process.env.VUE_APP_TITLE;
});
export { router };
